package cn.com.inossem.fragment;

import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.foxykeep.datadroid.requestmanager.Request;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.com.inossem.activity.AddFriendsActivity;
import cn.com.inossem.activity.FriendList;
import cn.com.inossem.activity.FriendsDetailsActivity;
import cn.com.inossem.activity.InviteShareDialogActivity;
import cn.com.inossem.activity.Manifest;
import cn.com.inossem.activity.MapActivity;
import cn.com.inossem.activity.R;
import cn.com.inossem.adapter.UserAdapter;
import cn.com.inossem.base.RequestFragment;
import cn.com.inossem.model.UserInfo;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.PingYinUtil;
import cn.com.inossem.utils.PinyinComparator;
import cn.com.inossem.utils.Utils;
import cn.com.inossem.utils.wangyi.session.SessionHelper;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MyFriendsFragment extends RequestFragment implements
		OnClickListener {
	public static MyFriendsFragment mf = null;
	UserAdapter user_adapter = null;
	public EditText text_phone = null;
	ListView list_view = null;
	private ListView listview;
	private ArrayList<String> webNameArr;
	List<Boolean> stateList = new ArrayList<Boolean>();
	int touchState;
	TextView ditu;
	ImageView sousuo, back, addfriend;
	EditText editText2;
	List<UserInfo> saveList = new ArrayList<UserInfo>();
	private ArrayList<String> saveNameArr = new ArrayList<String>();
	public static List<UserInfo> u_list = new ArrayList<UserInfo>();
	TextView yaoqing;
	private String py[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
			"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
			"X", "Y", "Z"};
	RelativeLayout morelayout;
	LinearLayout llayout01, llayout02, llayout03;

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// if (this.isVisible()) {
		// we check that the fragment is becoming visible
		if (isVisibleToUser) {
			mHasLoadedOnce = true;
			// onVisible();
			// lazyLoad();
		} else {
			mHasLoadedOnce = false;
			// onInvisible();
		}
		// }
		super.setUserVisibleHint(isVisibleToUser);
	}

	@Override
	public void initAllMembers(Bundle savedInstanceState) {
		super.initAllMembers(savedInstanceState);
		mf = this;
		initView();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mHasLoadedOnce)
			loading();
	}

	public void loading() {
		launchRequest(WooRequestFactory.friendslist());
	}

	public void initView() {
		morelayout = (RelativeLayout) mRootView.findViewById(R.id.morelayout);
		morelayout.setOnClickListener(this);
		llayout01 = (LinearLayout) mRootView.findViewById(R.id.llayout01);
		llayout01.setOnClickListener(this);
		llayout02 = (LinearLayout) mRootView.findViewById(R.id.llayout02);
		llayout02.setOnClickListener(this);
		llayout03 = (LinearLayout) mRootView.findViewById(R.id.llayout03);
		llayout03.setOnClickListener(this);

		sousuo = (ImageView) mRootView.findViewById(R.id.sousuo);
		sousuo.setOnClickListener(this);
		addfriend = (ImageView) mRootView.findViewById(R.id.addfriend);
		addfriend.setOnClickListener(this);
		ditu = (TextView) mRootView.findViewById(R.id.ditu);
		ditu.setOnClickListener(this);
		back = (ImageView) mRootView.findViewById(R.id.back);
		back.setOnClickListener(this);
		editText2 = (EditText) mRootView.findViewById(R.id.editText2);
		editText2.addTextChangedListener(textWatcher);
		yaoqing = (TextView) mRootView.findViewById(R.id.yaoqing);
		yaoqing.setOnClickListener(this);

		list_view = (ListView) mRootView.findViewById(R.id.listView1);

		listview = (ListView) mRootView.findViewById(R.id.listview);

		listview.setAdapter(new ListAdapter() {

			@Override
			public void unregisterDataSetObserver(DataSetObserver observer) {
				// TODO Auto-generated method stub

			}

			@Override
			public void registerDataSetObserver(DataSetObserver observer) {
				// TODO Auto-generated method stub

			}

			@Override
			public boolean isEmpty() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean hasStableIds() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public int getViewTypeCount() {
				// TODO Auto-generated method stub
				return 1;
			}

			private LayoutInflater inflater;

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				inflater = LayoutInflater.from(getActivity());
				convertView = inflater.inflate(R.layout.letter_layout, null);
				TextView text = (TextView) convertView;
				text.setTextSize(Utils.dip2px(getActivity(), 3));
				text.setHeight(listview.getHeight() / 26);
				text.setText(py[position]);
				// text.setTextColor(Color.WHITE);
				return text;
			}

			@Override
			public int getItemViewType(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return py.length;
			}

			@Override
			public boolean isEnabled(int position) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean areAllItemsEnabled() {
				// TODO Auto-generated method stub
				return false;
			}
		});
		listview.setDivider(null);
		// listview.setOnItemClickListener(this);
		listview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				touchState = event.getAction();
				int hightLevel = listview.getHeight() / 26;
				int position = (int) (event.getY() / hightLevel);
				if (position >= 0 && position < 26) {
					String s = py[position];
					// String s = ((TextView) view).getText().toString();
					// txtOverlay.setText(s);
					// txtOverlay.setVisibility(View.VISIBLE);
					// handler.removeCallbacks(disapearThread);
					// // 提示延迟1.5s再消失
					// handler.postDelayed(disapearThread, 1500);
					int localPosition = -1;
					if (u_list.size() > 0) {
						localPosition = binSearch(webNameArr, s); // 接收返回值
					}

					if (localPosition != -1) {
						// txtOverlay.setVisibility(View.INVISIBLE); //
						// 防止点击出现的txtOverlay与滚动出现的txtOverlay冲突
						list_view.setSelection(localPosition); // 让List指向对应位置的Item
					}
				}
				return false;
			}
		});
	}

	// 将选中的py与stringArr的首字符进行匹配并返回对应字符串在数组中的位置
	public static int binSearch(ArrayList<String> string, String s) {
		for (int i = 0; i < string.size(); i++) {
			if (s.equalsIgnoreCase("" + string.get(i).charAt(0))) { // ����ִ�Сд
				return i;
			}
		}
		return -1;

	}

	@Override
	public int getContentViewId() {
		// TODO Auto-generated method stub
		return R.layout.friendlist_layout;
	}

	// 处理返回值
	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		super.onRequestSucess(request, bundle);
		if (bundle.containsKey(WooRequestFactory.RESPONSE_FRIENDS_DATA)) {
			u_list = new ArrayList<UserInfo>();
			List<UserInfo> retList = bundle
					.getParcelableArrayList(WooRequestFactory.RESPONSE_FRIENDS_DATA);
			System.out.println("retList长度：" + retList.size());
			u_list = retList;
			for (int i = 0; i < u_list.size(); i++) {
				if (u_list.get(i).getTruename().equals("")) {
					u_list.get(i).setTruename("无");
				}
			}

			PinyinComparator comparator = new PinyinComparator();
			if (u_list.size() > 0)
				Collections.sort(u_list, comparator);
			webNameArr = new ArrayList<String>();
			for (int i = 0; i < u_list.size(); i++) {
				String py = PingYinUtil.getPingYin(u_list.get(i).getTruename());
				webNameArr.add(py);
				stateList.add(false);
			}

			user_adapter = new UserAdapter(getActivity(), u_list, webNameArr, this);
			list_view.setAdapter(user_adapter);

			list_view.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
				                        int arg2, long arg3) {
					Intent intent = new Intent(getActivity(), FriendsDetailsActivity.class);
					intent.putExtra("type", 1);
					intent.putExtra("toUserId", u_list.get(arg2).getId() + "");
					intent.putExtra("toUserName", u_list.get(arg2)
							.getNickname());
					intent.putExtra("phone", u_list.get(arg2).getUsername());
					startActivity(intent);
				}
			});
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
			case R.id.yaoqing:
				intent = new Intent(getActivity(), FriendList.class);
				startActivity(intent);
				break;
			case R.id.addfriend:
			/*intent = new Intent(getActivity(), AddFriendsActivity.class);
			startActivity(intent);
			break;*/
				if (morelayout.getVisibility() == View.VISIBLE) {
					morelayout.setVisibility(View.GONE);
				} else {
					morelayout.setVisibility(View.VISIBLE);
				}
				break;
			case R.id.ditu:
				intent = new Intent(getActivity(), MapActivity.class);
				startActivity(intent);
				break;
			case R.id.back:
				// finish();
				break;
			case R.id.sousuo:
				// String str = editText2.getText().toString();
				// if (str.equals("")) {
				// user_adapter.setInfoData(u_list, webNameArr);
				// user_adapter.notifyDataSetChanged();
				// } else {
				// saveList = new ArrayList<FriendInfoBean>();
				// saveNameArr = new ArrayList<String>();
				// for (int i = 0; i < u_list.size(); i++) {
				// System.out.println(u_list.get(i).toString()
				// + "--------1111---------" + str);
				// if (u_list.get(i).username.toString().contains(str)) {
				// // if (isHave(u_list.get(i).username, str)) {
				// saveList.add(u_list.get(i));
				// saveNameArr.add(webNameArr.get(i));
				// }
				// }
				// user_adapter.setInfoData(saveList, saveNameArr);
				// user_adapter.notifyDataSetChanged();
				// }
				break;
			case R.id.llayout03:
				intent = new Intent(getActivity(), AddFriendsActivity.class);
				startActivity(intent);
				morelayout.setVisibility(View.GONE);
				break;
			case R.id.llayout01:
				intent = new Intent(getActivity(), FriendList.class);
				startActivity(intent);
				morelayout.setVisibility(View.GONE);
				break;
			case R.id.llayout02:
				intent = new Intent(getActivity(), InviteShareDialogActivity.class);
				startActivity(intent);
				morelayout.setVisibility(View.GONE);
				break;
			case R.id.morelayout:
				morelayout.setVisibility(View.GONE);
				break;
			case R.id.textView3:
				UserInfo task = user_adapter.getItem((Integer) v.getTag());
				MyFriendsFragmentPermissionsDispatcher.startChatWithCheck(this, task);
				break;
		}
	}

	@NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
	public void startChat(UserInfo task) {
		List<String> accounts = new ArrayList<String>(1);
		accounts.add(task.getId() + "");
		NimUIKit.notifyUserInfoChanged(accounts);
		NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(task.getId() + "");
		NimUIKit.startChatting(getActivity(), task.getId() + "", SessionTypeEnum.P2P, SessionHelper.getP2pCustomization());
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		MyFriendsFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
	}

	private TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			Log.d("TAG", "afterTextChanged--------------->");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
		                              int after) {
			// TODO Auto-generated method stub
			Log.d("TAG", "beforeTextChanged--------------->");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
		                          int count) {
			Log.d("TAG", "onTextChanged--------------->");
			String str = editText2.getText().toString();
			if (str.equals("")) {
				if (user_adapter != null) {
					user_adapter.setInfoData(u_list, webNameArr);
					user_adapter.notifyDataSetChanged();
				}
			} else {
				saveList = new ArrayList<UserInfo>();
				saveNameArr = new ArrayList<String>();
				for (int i = 0; i < u_list.size(); i++) {
					System.out.println(u_list.get(i).toString()
							+ "--------1111---------" + str);
					if (u_list.get(i).getTruename().toString().contains(str)) {
						// if (isHave(u_list.get(i).username, str)) {
						saveList.add(u_list.get(i));
						saveNameArr.add(webNameArr.get(i));
					}
				}
				if (user_adapter != null) {
					user_adapter.setInfoData(saveList, saveNameArr);
					user_adapter.notifyDataSetChanged();
				}
			}
		}
	};

	public void removeObj() {
		if (user_adapter != null) {
			user_adapter.removeUser();
		}
	}

	public static boolean isHave(String strs, String s) {
		for (int i = 0; i < strs.length() - 1; i++) {
			for (int j = i + 1; j < strs.length(); j++) {
				if (s.toLowerCase()
						.contains(strs.toLowerCase().substring(i, j))) {
					return true;
				}
			}
		}
		return false;

	}

}
